<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <el-row :gutter="24">
        <!-- 左侧：头像和基本信息 -->
        <el-col :span="8">
          <el-card class="avatar-card" shadow="never">
            <template #header>
              <span>头像</span>
            </template>
            
                         <div class="avatar-section">
               <el-avatar 
                 :size="120" 
                 :src="getAvatarUrl(profileData.avatar_url)"
                 class="profile-avatar"
               >
                 {{ profileData.nickname?.charAt(0) || 'U' }}
               </el-avatar>
              
              <div class="avatar-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="showAvatarDialog = true"
                >
                  <el-icon><Upload /></el-icon>
                  更换头像
                </el-button>
              </div>
            </div>
            
            <!-- 基本信息 -->
            <div class="basic-info">
              <h4>基本信息</h4>
              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="用户ID">{{ profileData.id || '-' }}</el-descriptions-item>
                <el-descriptions-item label="用户名">{{ profileData.username || '-' }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ profileData.nickname || '-' }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ profileData.email || '-' }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="profileData.enabled ? 'success' : 'danger'">
                    {{ profileData.enabled ? '启用' : '禁用' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ formatDate(profileData.create_time) }}
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                  {{ formatDate(profileData.update_time) }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-card>
        </el-col>
        
        <!-- 右侧：编辑表单 -->
        <el-col :span="16">
          <el-card class="edit-card" shadow="never">
            <template #header>
              <span>编辑资料</span>
            </template>
            
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              :rules="profileRules"
              label-width="100px"
              @submit.prevent="handleSubmit"
            >
              <el-form-item label="用户名" prop="username">
                <el-input 
                  v-model="profileForm.username" 
                  disabled 
                  placeholder="用户名不可修改"
                />
              </el-form-item>
              
              <el-form-item label="昵称" prop="nickname">
                <el-input 
                  v-model="profileForm.nickname" 
                  placeholder="请输入昵称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input 
                  v-model="profileForm.email" 
                  placeholder="请输入邮箱"
                  type="email"
                />
              </el-form-item>
              
              <el-form-item label="头像URL" prop="avatar_url">
                <el-input 
                  v-model="profileForm.avatar_url" 
                  placeholder="请输入头像URL"
                />
                                 <div class="avatar-preview" v-if="profileForm.avatar_url">
                   <el-avatar 
                     :size="60" 
                     :src="getAvatarUrl(profileForm.avatar_url)"
                     class="preview-avatar"
                   >
                     {{ profileForm.nickname?.charAt(0) || 'U' }}
                   </el-avatar>
                 </div>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleSubmit"
                  :loading="loading"
                >
                  {{ loading ? '保存中...' : '保存修改' }}
                </el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    
         <!-- 头像上传对话框 -->
     <el-dialog 
       v-model="showAvatarDialog" 
       title="更换头像" 
       width="500px"
     >
       <div class="avatar-upload">
         <el-form :model="avatarForm" label-width="80px">
                       <el-form-item label="头像URL">
              <el-input 
                v-model="avatarForm.avatar_url" 
                placeholder="请输入头像URL或上传本地图片"
              />
              <div style="margin-top: 5px; font-size: 12px; color: #909399;">
                💡 提示：支持输入任意图片URL或上传本地图片。系统会自动去重，相同图片不会重复保存。百度、小红书等平台的图片会自动通过代理访问。
              </div>
              <div class="upload-actions">
                <el-upload
                  v-if="uploadEnabled"
                  ref="uploadRef"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :http-request="handleUpload"
                  accept="image/*"
                  class="upload-btn"
                >
                  <el-button type="text" size="small" :loading="uploadLoading">
                    <el-icon><Picture /></el-icon>
                    上传本地图片
                  </el-button>
                </el-upload>
                <el-button v-else type="text" size="small" disabled>
                  <el-icon><Picture /></el-icon>
                  文件上传已禁用
                </el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="testAvatarUrl"
                >
                  测试头像URL
                </el-button>
              </div>
            </el-form-item>
           
                                    
           
                       <el-form-item label="预览">
              <el-avatar 
                :size="100" 
                :src="getAvatarUrl(avatarForm.avatar_url)"
                class="upload-preview"
              >
                {{ profileData.nickname?.charAt(0) || 'U' }}
              </el-avatar>
            </el-form-item>
         </el-form>
       </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAvatarDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleAvatarUpload"
            :loading="avatarLoading"
          >
            {{ avatarLoading ? '上传中...' : '确认上传' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { getProfile, updateProfile, uploadAvatar, checkImageUrl, getProxyImageUrl } from '@/api/auth'
import { uploadAvatar as uploadAvatarFile } from '@/api/upload'
import { getConfigStatus } from '@/api/system'
import { useUserStore } from '@/stores/user'
import { convertToFullUrl, processImageUrl, prepareUrlForStorage, needsProxy } from '@/utils/urlUtils'

// 响应式数据
const profileData = ref({})
const loading = ref(false)
const avatarLoading = ref(false)
const showAvatarDialog = ref(false)
const uploadLoading = ref(false)
const uploadEnabled = ref(true) // 文件上传是否启用

// 用户store
const userStore = useUserStore()

// 表单引用
const profileFormRef = ref()
const uploadRef = ref()

// 检查配置状态
const checkConfigStatus = async () => {
  try {
    const response = await getConfigStatus()
    if (response.code === 200) {
      uploadEnabled.value = response.data.uploadEnabled
      if (!uploadEnabled.value) {
        console.log('文件上传功能已被禁用')
      }
    }
  } catch (error) {
    console.error('获取配置状态失败:', error)
  }
}

// 表单数据
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  avatar_url: ''
})

// 头像表单
const avatarForm = reactive({
  avatar_url: ''
})



// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '昵称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  avatar_url: [
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ]
}

// 获取个人资料
const fetchProfile = async () => {
  try {
    const response = await getProfile()
    if (response.code === 200) {
      profileData.value = response.data
      
      // 更新表单数据
      profileForm.username = response.data.username
      profileForm.nickname = response.data.nickname
      profileForm.email = response.data.email
      profileForm.avatar_url = response.data.avatar_url
      
      // 调试信息
      console.log('获取到的个人资料:', response.data)
      console.log('头像URL:', response.data.avatar_url)
    }
  } catch (error) {
    console.error('获取个人资料失败:', error)
    ElMessage.error('获取个人资料失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await profileFormRef.value.validate()
    
    loading.value = true
    
    const response = await updateProfile({
      nickname: profileForm.nickname,
      email: profileForm.email,
      avatar_url: profileForm.avatar_url
    })
    
    if (response.code === 200) {
      ElMessage.success('个人资料更新成功')
      
      // 使用Store的updateProfileAction来更新全局用户信息
      await userStore.updateProfileAction({
        nickname: profileForm.nickname,
        email: profileForm.email,
        avatar_url: profileForm.avatar_url
      })
      
      // 重新获取资料
      await fetchProfile()
      
      // 调试信息
      console.log('个人资料更新成功，全局用户信息已更新:', userStore.userInfo)
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    ElMessage.error('更新个人资料失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  profileFormRef.value.resetFields()
  // 恢复原始数据
  profileForm.nickname = profileData.value.nickname
  profileForm.email = profileData.value.email
  profileForm.avatar_url = profileData.value.avatar_url
}

// 文件上传前的验证
const beforeUpload = (file) => {
  // 检查文件上传是否启用
  if (!uploadEnabled.value) {
    ElMessage.error('文件上传功能已被管理员禁用')
    return false
  }
  
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 检查文件大小（5MB）
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片文件大小不能超过5MB')
    return false
  }
  
  return true
}

// 处理文件上传
const handleUpload = async (options) => {
  const { file } = options
  
  try {
    uploadLoading.value = true
    
    const response = await uploadAvatarFile(file)
    
    if (response.code === 200) {
      // 根据是否为新文件显示不同的提示
      if (response.data.isNewFile) {
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.success('图片已存在，直接使用现有文件')
      }
      
      // 将上传后的图片URL设置到表单中（转换为完整URL）
      avatarForm.avatar_url = convertToFullUrl(response.data.fileUrl)
      
      console.log('文件信息:', {
        fileName: response.data.fileName,
        fileHash: response.data.fileHash,
        isNewFile: response.data.isNewFile,
        fileUrl: response.data.fileUrl
      })
    } else if (response.code === 403) {
      // 文件上传功能被禁用
      ElMessage.error('文件上传功能已被管理员禁用，请联系管理员')
    } else {
      ElMessage.error(response.message || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 头像上传
const handleAvatarUpload = async () => {
  if (!avatarForm.avatar_url) {
    ElMessage.warning('请输入头像URL')
    return
  }
  
  try {
    avatarLoading.value = true
    
    const response = await uploadAvatar(avatarForm.avatar_url)
    
         if (response.code === 200) {
       ElMessage.success('头像上传成功')
       showAvatarDialog.value = false
       
       // 清空头像表单
       avatarForm.avatar_url = ''
       
       // 强制更新头像显示
       await nextTick()
       
       // 使用Store的updateAvatarAction来更新全局用户信息
       await userStore.updateAvatarAction(response.data.avatar_url)
       
       // 重新获取用户信息以确保头像更新
       await userStore.getUserInfoAction()
       
       // 重新获取资料
       await fetchProfile()
       
       // 强制刷新页面以确保所有组件都更新
       setTimeout(() => {
         console.log('延迟后的头像URL:', userStore.userInfo.avatar_url)
         // 如果状态仍然不同步，强制刷新页面
         if (userStore.userInfo.avatar_url !== response.data.avatar_url) {
           console.log('状态不同步，强制刷新页面')
           // 清理可能的缓存
           if ('caches' in window) {
             caches.keys().then(names => {
               names.forEach(name => {
                 caches.delete(name)
               })
             })
           }
           window.location.reload()
         }
       }, 500)
       
       // 调试信息
       console.log('头像上传成功，新头像URL:', response.data.avatar_url)
       console.log('全局用户信息已更新:', userStore.userInfo)
       console.log('当前头像URL:', userStore.userInfo.avatar_url)
     } else {
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  } finally {
    avatarLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 测试头像URL
const testAvatarUrl = async () => {
  if (!avatarForm.avatar_url) {
    ElMessage.warning('请先输入头像URL')
    return
  }
  
  const url = avatarForm.avatar_url
  console.log('开始测试头像URL:', url)
  
  try {
    // 首先尝试通过代理检查
    const checkResponse = await checkImageUrl(url)
    console.log('代理检查结果:', checkResponse)
    
    if (checkResponse.code === 200 && checkResponse.status === 'success') {
      ElMessage.success('头像URL有效，可以通过代理访问')
      console.log('头像测试成功 (通过代理):', url)
      
      // 显示代理后的URL
      const proxyUrl = getProxyImageUrl(url)
      console.log('代理URL:', proxyUrl)
      
      // 测试代理URL是否可加载
      const img = new Image()
      img.onload = () => {
        ElMessage.success('头像URL有效，可以正常加载')
        console.log('代理图片加载成功:', proxyUrl)
        console.log('图片尺寸:', img.width, 'x', img.height)
      }
      
      img.onerror = (e) => {
        console.error('代理图片加载失败:', proxyUrl)
        ElMessage.warning('图片可通过代理访问，但加载失败，请稍后重试')
      }
      
      img.src = proxyUrl
    } else {
      // 如果代理检查失败，尝试直接加载
      const img = new Image()
      img.crossOrigin = 'anonymous'
      
      img.onload = () => {
        ElMessage.success('头像URL有效，可以正常加载')
        console.log('头像测试成功 (直接访问):', url)
        console.log('图片尺寸:', img.width, 'x', img.height)
      }
      
      img.onerror = (e) => {
        console.error('头像测试失败:', url)
        console.error('错误详情:', e)
        
        // 根据错误类型提供不同的提示
        if (needsProxy(url)) {
          ElMessage.error('该图片服务有访问限制，无法直接使用')
          ElMessage.warning('系统会自动通过代理访问，请重试')
        } else {
          ElMessage.error('头像URL无效，无法加载图片')
          ElMessage.warning('请检查URL是否正确')
        }
      }
      
      img.src = url
    }
  } catch (error) {
    console.error('测试头像URL时发生错误:', error)
    ElMessage.error('测试失败，请检查网络连接')
  }
}



// 获取头像URL（支持代理和本地文件）
const getAvatarUrl = (url) => {
  return processImageUrl(url)
}

// 组件挂载时获取资料
onMounted(() => {
  checkConfigStatus()
  fetchProfile()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.avatar-card {
  .avatar-section {
    text-align: center;
    margin-bottom: 20px;
    
    .profile-avatar {
      margin-bottom: 15px;
      border: 3px solid #e6e6e6;
    }
    
    .avatar-actions {
      margin-top: 10px;
    }
  }
  
  .basic-info {
    h4 {
      margin: 0 0 15px 0;
      color: #303133;
      font-size: 16px;
    }
  }
}

.edit-card {
  .avatar-preview {
    margin-top: 10px;
    text-align: center;
    
    .preview-avatar {
      border: 2px solid #e6e6e6;
    }
  }
}

.avatar-upload {
  .upload-preview {
    border: 2px solid #e6e6e6;
  }
}

.upload-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.upload-btn {
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

// 响应式设计
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
}
</style>
